import axios from "axios";
import qs from 'qs'
// http request 拦截器
axios.interceptors.request.use(
    config => {
        config.headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        };
        let url = config.url;
        if (url != null && url.indexOf('/api/') === -1) {
            config.baseURL = axios.defaults.baseURL + '/admin';
        }

        console.log(config.baseURL);

        if (config.method === 'post' || config.method == 'put') {
            config.data = qs.stringify(config.data);
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        if (error.response) {
            console.log("请求错误");
            console.log(error.response.status);
            let url = location.href;
            switch (error.response.status) {
                case 401:
                    //跳转到授权页
                    console.log("授权失败！");
                    console.log(url);

                    //window.localStorage.removeItem('token');
                    window.localStorage.setItem('beforeLoginUrl', url);
                    router.push({path: '/weixin/auth'});
                    // store.dispatch('logout');
                    console.log("401");
                    break;
                case 402:
                    //跳转到授权页
                    console.log("授权失败！402");
                    console.log(url);

                    //window.localStorage.removeItem('token');
                    window.localStorage.setItem('beforeLoginUrl', url);
                    window.localStorage.setItem('isVip', "1");
                    router.push({path: '/weixin/auth'});
                    // store.dispatch('logout');
                    console.log("402");
                    break;
                /*case 422:
                    var data = error.response.data;
                    console.log(data);
                    this.$message('这是一条消息提示');
                    this.$message({
                        message: data.error.msg,
                        type: 'warning'
                    });
                    break;*/
                /*case 404:
                    router.push('/Error/Error404');
                    break;*/
                case 500:
                    router.push('/search/errpage');
                    break;

            }

        }
        return Promise.reject(error);// 返回接口返回的错误信息
    });

export default axios;
